package com.xinzhi.service.impl;

import com.xinzhi.mapper.UserMapper;
import com.xinzhi.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SpringUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper usermapper;
    @Override
    public UserDetails loadUserByUsername(String phonenumber) throws UsernameNotFoundException {
        User user = usermapper.selectByUsername(phonenumber);
        if (user==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //获得角色列表
        List<String> roleCodes = usermapper.selectRolesByUserId(user.getUid());
        user.setRole(roleCodes);
        //通过角色列表获取权限列表
        List<String> menus = usermapper.selectMenuByRoles(roleCodes);
        roleCodes = roleCodes.stream().distinct().map(r -> "ROLE_" +   r).collect(Collectors.toList());
        menus.addAll(roleCodes);
        user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",",menus)));
        return user;
    }
}
